package com.lykj.modules.shop.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.lykj.common.cache.ParamCache;
import com.lykj.core.log.exception.ServiceException;
import com.lykj.core.secure.utils.AuthUtil;
import com.lykj.core.tool.utils.Func;
import com.lykj.modules.shop.entity.StoreCategory;
import com.lykj.modules.shop.entity.StoreProduct;
import com.lykj.modules.shop.entity.UserOrder;
import com.lykj.modules.shop.excel.UserOrderExcel;
import com.lykj.modules.shop.service.StoreCategoryService;
import com.lykj.modules.shop.service.StoreProductService;
import com.lykj.modules.shop.service.UserBillService;
import com.lykj.modules.shop.vo.UserOrderVO;
import com.lykj.modules.shop.mapper.UserOrderMapper;
import com.lykj.modules.shop.service.UserOrderService;
import com.lykj.core.mp.base.BaseServiceImpl;
import com.lykj.modules.shop.znapi.ZnApiUtils;
import com.lykj.modules.system.entity.User;
import com.lykj.modules.system.service.UserService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 现金订单表 服务实现类
 *
 * @author cxl
 * @since 2022-01-16
 */
@Service
public class UserOrderServiceImpl extends BaseServiceImpl<UserOrderMapper, UserOrder> implements UserOrderService {
	private final StoreCategoryService storeCategoryService;
	private final StoreProductService storeProductService;
	private final UserService userService;
	private final UserBillService userBillService;
	private final ZnApiUtils znApiUtils;

	// 超限金额
	public static Map<Integer, BigDecimal> limit = new HashMap<>();
	// 复购金额
	public static Map<Integer, BigDecimal> repeat = new HashMap<>();
	// 极差值
	public static Map<Integer, BigDecimal> value = new HashMap<>();
	// 自消费额度
	public static Map<Integer, BigDecimal> onw = new HashMap<>();
	// 团队业绩
	public static Map<Integer, BigDecimal> team = new HashMap<>();
	// 升级对应级别会员数量
	public static Map<Integer, Integer> num = new HashMap<>();

	public UserOrderServiceImpl(StoreCategoryService storeCategoryService, StoreProductService storeProductService, UserService userService, UserBillService userBillService, ZnApiUtils znApiUtils) {
		this.storeCategoryService = storeCategoryService;
		this.storeProductService = storeProductService;
		this.userService = userService;
		this.userBillService = userBillService;
		this.znApiUtils = znApiUtils;
	}

	@Override
	public IPage<UserOrderVO> selectUserOrderPage(IPage<UserOrderVO> page, UserOrderVO userOrder) {
		return page.setRecords(baseMapper.selectUserOrderPage(page, userOrder));
	}

	@Override
	public List<UserOrderExcel> export(UserOrderVO userOrder) {
		List<UserOrderExcel> userList = baseMapper.export(userOrder);
		return userList;
	}

	/**
	 * 保存现金订单
	 *
	 * @param tenantId
	 * @param userId
	 * @param contacts
	 * @param mobile
	 * @param shippingAddress
	 * @param storeProduct
	 * @param number
	 * @param payType
	 * @param status
	 * @param remark
	 */
	@Override
	public UserOrder insertMoneyOrder(String tenantId,
									  Long userId,
									  String contacts,
									  String mobile,
									  String shippingAddress,
									  StoreProduct storeProduct,
									  BigDecimal number,
									  int payType,
									  int status,
									  String deliveryApplyId,
									  String remark) {
		if (payType == 2 && status == 1) {
			// 众鸟收货订单 不减库存
			System.out.println("众鸟收货订单 不再减库存");
		} else {
			//增加销量，减少库存
			if(storeProductService.updateReserveAndSales(storeProduct.getId(),number.intValue())<1){
				throw new ServiceException("库存不足");
			}
		}
		BigDecimal orderPostage = storeProduct.getExpressFee().multiply(number);
		//获取分类信息
		StoreCategory storeCategory = storeCategoryService.getById(storeProduct.getCateId());
		//保存订单
		UserOrder userOrder = new UserOrder();
		userOrder.setTenantId(tenantId);
		userOrder.setUserId(userId);//用户ID
		userOrder.setContacts(contacts);//用户姓名
		userOrder.setMobile(mobile);//用户电话
		userOrder.setShippingAddress(shippingAddress);//详细地址
		userOrder.setCateId(storeProduct.getCateId());//商品分类ID
		userOrder.setBrokerageRatio(storeCategory.getBrokerageRatio());//返佣百分比
		userOrder.setAwardBrokerage(storeCategory.getAwardBrokerage());//奖励佣金0否1是
		userOrder.setAwardIntegral(storeCategory.getAwardIntegral());//奖励积分0否1是
		userOrder.setAwardContribute(storeCategory.getAwardContribute());//奖励贡献值0否1是
		userOrder.setAwardRange(storeCategory.getAwardRange());//奖励极差0否1是
		userOrder.setAwardBonus(storeCategory.getAwardBonus());//奖励红包0否1是
		userOrder.setProductId(storeProduct.getId());//商品ID
		userOrder.setZnCommodityId(storeProduct.getZnCommodityId());
		userOrder.setProductTitle(storeProduct.getTitle());//商品标题
		userOrder.setProductPostage(storeProduct.getExpressFee());//运费金额
		userOrder.setProductPvPrice(storeProduct.getPvPrice());//商品pv值
		userOrder.setPvTotalPrice(storeProduct.getPvPrice().multiply(number));//商品总pv值=商品pv值*购买数量
		userOrder.setTotalPrice(storeProduct.getSellPrice().multiply(number));//订单总价=商品价格*购买数量 不含运费
		userOrder.setProductSellPrice(storeProduct.getSellPrice());//商品单价
		userOrder.setTotalNum(number.intValue());//商品总数
		userOrder.setPayPrice(userOrder.getTotalPrice().add(orderPostage));//实际支付金额（含运费）=订单总价+运费
		userOrder.setPaid(1);//支付状态
		userOrder.setPayTime(new Date());//支付时间
		userOrder.setPayType(payType);//支付方式0平台余额1平台积分2众鸟余额
		userOrder.setRemark(remark);//备注
		userOrder.setStatus(status);//-1未发货0未收货1已收货
		if (status == 1) {
			userOrder.setConfirmTime(new Date());
		}
		if (!Func.isNull(deliveryApplyId)) {
			userOrder.setThirdOrder(deliveryApplyId);
		}
		this.save(userOrder);
		// 新建订单
		if (status == -1) {
			// TODO 分配分红资格
			this.bonusStatus(userOrder);
			// TODO 查询是否第一单
//			Integer count = this.list(Wrappers.<UserOrder>lambdaQuery()
//				.eq(UserOrder::getUserId, userOrder.getUserId())
//				.eq(UserOrder::getPaid, 1)// 支付成功
//				.ne(UserOrder::getPayType, 1)// 支付方式0平台余额1平台积分2众鸟余额
//			).size();
//			if (count == 1) {
//				this.awardIntegral(userOrder);
//			}
		}
		return userOrder;
	}

	public UserOrder createOrderInfo(String tenantId,
									  Long userId,
									  String contacts,
									  String mobile,
									  String shippingAddress,
									  StoreProduct storeProduct,
									  BigDecimal number,
									  int payType,
									  int status,
									  String deliveryApplyId,
									  String remark) {
		if (payType == 2 && status == 1) {
			// 众鸟收货订单 不减库存
			System.out.println("众鸟收货订单 不再减库存");
		} else {
			//增加销量，减少库存
			if(storeProductService.updateReserveAndSales(storeProduct.getId(), number.intValue())<1){
				throw new ServiceException("库存不足");
			}
		}
		BigDecimal orderPostage = storeProduct.getExpressFee().multiply(number);
		//获取分类信息
		StoreCategory storeCategory = storeCategoryService.getById(storeProduct.getCateId());
		//保存订单
		UserOrder userOrder = new UserOrder();
		userOrder.setTenantId(tenantId);
		userOrder.setUserId(userId);//用户ID
		userOrder.setContacts(contacts);//用户姓名
		userOrder.setMobile(mobile);//用户电话
		userOrder.setShippingAddress(shippingAddress);//详细地址
		userOrder.setCateId(storeProduct.getCateId());//商品分类ID
		userOrder.setBrokerageRatio(storeCategory.getBrokerageRatio());//返佣百分比
		userOrder.setAwardBrokerage(storeCategory.getAwardBrokerage());//奖励佣金0否1是
		userOrder.setAwardIntegral(storeCategory.getAwardIntegral());//奖励积分0否1是
		userOrder.setAwardContribute(storeCategory.getAwardContribute());//奖励贡献值0否1是
		userOrder.setAwardRange(storeCategory.getAwardRange());//奖励极差0否1是
		userOrder.setAwardBonus(storeCategory.getAwardBonus());//奖励红包0否1是
		userOrder.setProductId(storeProduct.getId());//商品ID
		userOrder.setZnCommodityId(storeProduct.getZnCommodityId());
		userOrder.setProductTitle(storeProduct.getTitle());//商品标题
		userOrder.setProductPostage(storeProduct.getExpressFee());//运费金额
		userOrder.setProductPvPrice(storeProduct.getPvPrice());//商品pv值
		userOrder.setPvTotalPrice(storeProduct.getPvPrice().multiply(number));//商品总pv值=商品pv值*购买数量
		userOrder.setTotalPrice(storeProduct.getSellPrice().multiply(number));//订单总价=商品价格*购买数量 不含运费
		userOrder.setProductSellPrice(storeProduct.getSellPrice());//商品单价
		userOrder.setTotalNum(number.intValue());//商品总数
		userOrder.setPayPrice(userOrder.getTotalPrice().add(orderPostage));//实际支付金额（含运费）=订单总价+运费
		userOrder.setPaid(1);//支付状态
		userOrder.setPayTime(new Date());//支付时间
		userOrder.setPayType(payType);//支付方式0平台余额1平台积分2众鸟余额
		userOrder.setRemark(remark);//备注
		userOrder.setStatus(status);//-1未发货0未收货1已收货
		if (status == 1) {
			userOrder.setConfirmTime(new Date());
		}
		if (!Func.isNull(deliveryApplyId)) {
			userOrder.setThirdOrder(deliveryApplyId);
		}
		this.save(userOrder);
		return userOrder;
	}

	/**
	 * 保存积分订单
	 *
	 * @param tenantId
	 * @param userId
	 * @param contacts
	 * @param mobile
	 * @param shippingAddress
	 * @param storeProduct
	 * @param number
	 * @param payType
	 * @param status
	 * @param remark
	 */
	@Override
	public UserOrder insertIntegralOrder(String tenantId,
										 Long userId,
										 String contacts,
										 String mobile,
										 String shippingAddress,
										 StoreProduct storeProduct,
										 BigDecimal number,
										 int payType,
										 int status,
										 String deliveryApplyId,
										 String remark) {
		//增加销量，减少库存
		if(storeProductService.updateReserveAndSales(storeProduct.getId(),number.intValue())<1){
			throw new ServiceException("库存不足");
		}
		//获取分类信息
		StoreCategory storeCategory = storeCategoryService.getById(storeProduct.getCateId());
		//保存订单
		UserOrder userOrder = new UserOrder();
		userOrder.setTenantId(tenantId);
		userOrder.setUserId(userId);//用户ID
		userOrder.setContacts(contacts);//用户姓名
		userOrder.setMobile(mobile);//用户电话
		userOrder.setShippingAddress(shippingAddress);//详细地址
		userOrder.setCateId(storeProduct.getCateId());//商品分类ID
		userOrder.setBrokerageRatio(storeCategory.getBrokerageRatio());//返佣百分比
		userOrder.setAwardBrokerage(storeCategory.getAwardBrokerage());//奖励佣金0否1是
		userOrder.setAwardIntegral(storeCategory.getAwardIntegral());//奖励积分0否1是
		userOrder.setAwardContribute(storeCategory.getAwardContribute());//奖励贡献值0否1是
		userOrder.setAwardRange(storeCategory.getAwardRange());//奖励极差0否1是
		userOrder.setAwardBonus(storeCategory.getAwardBonus());//奖励红包0否1是
		userOrder.setProductId(storeProduct.getId());//商品ID
		userOrder.setZnCommodityId(storeProduct.getZnCommodityId());
		userOrder.setProductTitle(storeProduct.getTitle());//商品标题
//		userOrder.setProductDescription(storeProduct.getDetail());//商品详情json
		userOrder.setProductPostage(storeProduct.getExpressFee());//运费金额
		userOrder.setProductPvPrice(storeProduct.getPvPrice());//商品pv值
		userOrder.setPvTotalPrice(storeProduct.getPvPrice().multiply(number));//商品总pv值=商品pv值*购买数量
		userOrder.setTotalPrice(storeProduct.getIntegral().multiply(number));//订单总积分=商品积分*数量 不含运费
		userOrder.setProductSellPrice(storeProduct.getIntegral());//商品单价积分
		userOrder.setTotalNum(number.intValue());//商品总数
		userOrder.setPayPrice(storeProduct.getIntegral().multiply(number));//实际支付积分
		userOrder.setPaid(1);//支付状态
		userOrder.setPayTime(new Date());//支付时间
		userOrder.setPayType(payType);//支付方式0平台余额1平台积分2众鸟余额
		userOrder.setRemark(remark);//备注
		userOrder.setStatus(status);//-1未发货0未收货1已收货
		if (status == 1) {
			userOrder.setConfirmTime(new Date());
		}
		if (!Func.isNull(deliveryApplyId)) {
			userOrder.setThirdOrder(deliveryApplyId);
		}
		this.save(userOrder);
		return userOrder;
	}

	/**
	 * 更改处理状态
	 *
	 * @param id
	 */
	@Override
	public void dispose(Long id) {
		baseMapper.dispose(id);
	}

	/**
	 * 停止分红
	 *
	 * @param id
	 */
	@Override
	public void stopBonus(Long id) {
		baseMapper.stopBonus(id);
	}

	/**
	 * 累加分红金额
	 *
	 * @param number
	 * @param id
	 */
	@Override
	public void totalBonus(BigDecimal number, Long id) {
		baseMapper.totalBonus(number, id);
	}

	/**
	 * 积分兑换
	 *
	 * @param params
	 * @return
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean redeem(Map<String, Object> params) {
		if (Func.isNull(params.get("productId")) || Func.isNull(params.get("number")) || Func.isNull(params.get("payType"))) {
			throw new ServiceException("请选择商品！");
		}
		User user = userService.getById(AuthUtil.getUserId());
//		BigDecimal userBalance = user.getSysBalance();
//		BigDecimal userIntegral = user.getSysIntegral();
		Integer payType = Integer.parseInt(params.get("payType").toString());
		Long productId = Long.parseLong(params.get("productId").toString());
		Integer number = Integer.parseInt(params.get("number").toString());
		if (number <= 0) {
			throw new ServiceException("请选择商品！");
		}
		// 商品信息
		StoreProduct storeProduct = storeProductService.getOne(Wrappers.<StoreProduct>lambdaQuery()
			.eq(StoreProduct::getTenantId, AuthUtil.getTenantId())
			.eq(StoreProduct::getId, productId));
		if (Func.isNull(storeProduct)) {
			throw new ServiceException("非法操作！");
		}
		if (storeProduct.getReserveCount()<=0){
			throw new ServiceException("暂无库存！");
		}
		// TODO 订单运费
		BigDecimal orderPostage = storeProduct.getExpressFee().multiply(new BigDecimal(number));
		// TODO 订单商品金额或积分
		BigDecimal payPrice = BigDecimal.ZERO;
		if (payType == 0) {
			// 余额支付 商品售价*数量
			payPrice = storeProduct.getSellPrice().multiply(new BigDecimal(number));//.add(storeProduct.getExpressFee());
			if (user.getSysBalance().compareTo(payPrice.add(orderPostage)) < 0 || payPrice.compareTo(BigDecimal.ZERO) <= 0) {
				throw new ServiceException("平台账户余额不足，无法完成购买");
			}
			// 扣除余额
			userService.decBalance(payPrice, user.getId());
		} else if(payType==1){// 积分支付
			if (storeProduct.getIsIntegral() == 0) {
				throw new ServiceException("当前商品非积分兑换商品！");
			}
			//商品兑换积分*数量
			payPrice = storeProduct.getIntegral().multiply(new BigDecimal(number));
			//判断积分
			if (user.getSysIntegral().compareTo(payPrice) < 0 || payPrice.compareTo(BigDecimal.ZERO) <= 0) {
				throw new ServiceException("账户积分不足，无法完成兑换");
			}
			//判断运费
			if (user.getSysBalance().compareTo(orderPostage) < 0) {
				throw new ServiceException("账户余额不足，无法完成兑换");
			}
			// 扣除积分
			userService.decIntegral(payPrice, user.getId());
			// 扣除运费
			userService.decBalance(orderPostage, user.getId());
		} else if(payType==3){// 专项金支付
			payPrice = storeProduct.getSellPrice().multiply(new BigDecimal(number));//.add(storeProduct.getExpressFee());
			if (user.getEarmarkedMoney().compareTo(payPrice.add(orderPostage)) < 0 || payPrice.compareTo(BigDecimal.ZERO) <= 0) {
				throw new ServiceException("专享金账户余额不足，无法完成购买");
			}
			// 扣除余额
			userService.decEarmarkedMoney(payPrice, user.getId());
		}
		// 生成订单
		UserOrder userOrder = null;
		if (payType == 1) {
			userOrder = this.insertIntegralOrder(user.getTenantId(),
				user.getId(),
				params.get("contacts").toString(),
				params.get("mobile").toString(),
				params.get("shippingAddress").toString(),
				storeProduct,
				BigDecimal.valueOf(number),
				payType,
				-1,
				null,
				"积分兑换");
		} else if (payType == 0) {
			userOrder = this.insertMoneyOrder(user.getTenantId(),
				user.getId(),
				params.get("contacts").toString(),
				params.get("mobile").toString(),
				params.get("shippingAddress").toString(),
				storeProduct,
				BigDecimal.valueOf(number),
				payType,
				-1,
				null,
				"余额购买");
		}else if (payType == 3) {
			userOrder = this.insertMoneyOrder(user.getTenantId(),
				user.getId(),
				params.get("contacts").toString(),
				params.get("mobile").toString(),
				params.get("shippingAddress").toString(),
				storeProduct,
				BigDecimal.valueOf(number),
				payType,
				-1,
				null,
				"专项金购买");
		}
		//运费扣除记录
		if (orderPostage.compareTo(BigDecimal.ZERO) > 0) {
//			userBalance = userBalance.subtract(orderPostage);
			userBillService.insertBill(
				user.getTenantId(),
				user.getId(),
				0L,
				userOrder.getId(),
				0,//0转出1转入
				orderPostage,
				BigDecimal.ZERO,
				"平台订单支付运费",
				0,//0现金1积分2贡献值
				10,//0增加1减少2奖励3兑换4充值5提现6购物7转账8红包9收益10运费
//				userBalance,
				"平台订单支付运费,运费[" + orderPostage + "],手续费[" + BigDecimal.ZERO + "],实际金额[" + orderPostage + "]"//,余额[" + userBalance + "]
			);
		}
		//积分扣除记录
		if (payType == 1) {
			// 扣除积分
//			userIntegral = userIntegral.subtract(payPrice);
			userBillService.insertBill(
				user.getTenantId(),
				user.getId(),
				0L,
				userOrder.getId(),
				0,//0转出1转入
				payPrice,
				BigDecimal.ZERO,
				"平台积分兑换",
				1,//0现金1积分2贡献值
				3,//0增加1减少2奖励3兑换4充值5提现6购物7转账8红包9收益10运费
//				userIntegral,
				"平台积分兑换,积分[" + payPrice + "],手续费[" + BigDecimal.ZERO + "],实际金额[" + payPrice + "]"//,余额[" + userIntegral + "]
			);
		} else if (payType == 0) {
			// 扣除支付金额
//			userBalance = userBalance.subtract(payPrice);
			userBillService.insertBill(
				user.getTenantId(),
				user.getId(),
				0L,
				userOrder.getId(),
				0,//0转出1转入
				payPrice,
				BigDecimal.ZERO,
				"平台余额购买",
				0,//0现金1积分2贡献值
				6,//0增加1减少2奖励3兑换4充值5提现6购物7转账8红包9收益10运费
//				userBalance,
				"平台余额购买,现金[" + payPrice + "],手续费[" + BigDecimal.ZERO + "],实际金额[" + payPrice + "]"//,余额[" + userBalance + "]
			);
		}else if (payType == 3) {
			userBillService.insertBill(
					user.getTenantId(),
					user.getId(),
					0L,
					userOrder.getId(),
					0,//0转出1转入
					payPrice,
					BigDecimal.ZERO,
					"专项金购买",
					3,//0现金1积分2贡献值
					6,//0增加1减少2奖励3兑换4充值5提现6购物7转账8红包9收益10运费
//				userBalance,
					"专项金购买购买,现金[" + payPrice + "],手续费[" + BigDecimal.ZERO + "],实际金额[" + payPrice + "]"//,余额[" + userBalance + "]
			);
		}
//		if (payType == 0) {
//			// TODO 分配分红资格
//			this.bonusStatus(userOrder);
//			// TODO 查询是否第一单
//			Integer count = this.list(Wrappers.<UserOrder>lambdaQuery()
//				.eq(UserOrder::getUserId, user.getId())
//				.eq(UserOrder::getPaid, 1)// 支付成功
//				.ne(UserOrder::getPayType, 1)// 支付方式0平台余额1平台积分2众鸟余额
//			).size();
//			if (count == 1) {
//				this.awardIntegral(userOrder);
//			}
//		}
		// TODO 激活分流平台 二级解冻资格
		if (payType == 0 && payPrice.compareTo(BigDecimal.valueOf(299)) > -1) {
			znApiUtils.brokerageTwoStatus(user.getTenantId(), user.getAccount());
		}
		return true;
	}

	/**
	 * 积分兑换
	 *
	 * @param params
	 * @return
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public UserOrder wxredeem(Map<String, Object> params) {
		if (Func.isNull(params.get("productId")) || Func.isNull(params.get("number"))) {
			throw new ServiceException("请选择商品！");
		}
		User user = userService.getById(AuthUtil.getUserId());
		Long productId = Long.parseLong(params.get("productId").toString());
		Integer number = Integer.parseInt(params.get("number").toString());
		if (number <= 0) {
			throw new ServiceException("请选择商品！");
		}
		// 商品信息
		StoreProduct storeProduct = storeProductService.getOne(Wrappers.<StoreProduct>lambdaQuery()
				.eq(StoreProduct::getTenantId, AuthUtil.getTenantId())
				.eq(StoreProduct::getId, productId));
		if (Func.isNull(storeProduct)) {
			throw new ServiceException("非法操作！");
		}
		return createOrderInfo(user.getTenantId(),
				user.getId(),
				params.get("contacts").toString(),
				params.get("mobile").toString(),
				params.get("shippingAddress").toString(),
				storeProduct,
				BigDecimal.valueOf(number),
				0,
				-2,
				null,
				"小程序支付购买");
	}

	/**
	 * 确认收货
	 *
	 * @param userOrder
	 */
	@Override
	public void confirmReceipt(UserOrder userOrder) {
		// 获取相应规则
		JSONArray memberSystemRule = JSONArray.parseArray(ParamCache.getValue("member.system.rule"));
		if (memberSystemRule instanceof JSONArray) {
			memberSystemRule.stream().forEach(x -> {
				JSONObject object = (JSONObject) x;
				num.put(object.getInteger("no"), object.getInteger("num"));
				repeat.put(object.getInteger("no"), object.getBigDecimal("repeat"));
				limit.put(object.getInteger("no"), object.getBigDecimal("limit"));
				onw.put(object.getInteger("no"), object.getBigDecimal("onw"));
				team.put(object.getInteger("no"), object.getBigDecimal("team"));
				value.put(object.getInteger("no"), object.getBigDecimal("value"));
			});
		}
		// 修改订单处理状态
		this.dispose(userOrder.getId());
		// 获取用户信息
		User user = userService.getById(userOrder.getUserId());
		// 累计订单总额
		userService.inOrdersTotal(userOrder.getTotalPrice(), user.getId());
		//将红包类商品金额更新当前客户累计消费金额
		if (userOrder.getAwardBonus() == 1) {
			userService.inBonusOrders(userOrder.getPvTotalPrice(), user.getId());
		}
		//获取收货记录数
		Integer count = this.list(Wrappers.<UserOrder>lambdaQuery()
			.eq(UserOrder::getUserId, userOrder.getUserId())
			.eq(UserOrder::getPaid, 1)// 支付成功
			.ne(UserOrder::getPayType, 1)// 支付方式0平台余额1平台积分2众鸟余额
			.eq(UserOrder::getStatus, 1)//收货成功订单
		).size();
		// 如果是第一单，并且跨月收货，多送一次红包资格
		if (count == 1 && user.getBonusStatus() == 0) {
			userService.bonusStatus(1, user.getId());
		}
		// TODO 判断是否有推荐人
		if (user.getSpreadId() != null || user.getSpreadId() != 0L) {
			//获取推荐人信息
			User referrer = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getUid, user.getSpreadId()));
			if (referrer != null) {
//				BigDecimal referrerBalance = referrer.getSysBalance();
//				BigDecimal referrerIntegral = referrer.getSysIntegral();
//				BigDecimal referrerContribute = referrer.getSysContribute();
				// TODO 一.佣金类商品 上级直返5%现金收益
				BigDecimal brokeragePrice = userOrder.getPvTotalPrice().multiply(userOrder.getBrokerageRatio());
				if (userOrder.getAwardBrokerage() == 1 && brokeragePrice.compareTo(BigDecimal.ZERO) > 0) {
					// 上级直返5%现金收益
					userService.inBalance(brokeragePrice, referrer.getId());

//					referrerBalance = referrerBalance.add(brokeragePrice);
					//佣金奖励记录
					userBillService.insertBill(
						referrer.getTenantId(),
						referrer.getId(),
						user.getId(),
						userOrder.getId(),
						1,//0转出1转入
						brokeragePrice,
						BigDecimal.ZERO,
						"推荐奖励",
						0,//0现金1积分2贡献值
						2,//0增加1减少2奖励3兑换4充值5提现6购物7转账8红包9收益10运费
//						referrerBalance,
						"推荐奖励,订单[" + userOrder.getId() + "],推荐[" + user.getId() + "],金额[" + brokeragePrice + "],手续费[" + BigDecimal.ZERO + "],实际到账[" + brokeragePrice + "]"//,余额[" + referrerBalance + "]
					);
				}
				/**
				 // TODO 奖励推荐人首单积分 订单金额*奖励积分比例
				 if(count == 1){
				 // 查询第一单 支付成功且非积分订单
				 List<UserOrder> oneUserOrder = this.list(Wrappers.<UserOrder>lambdaQuery()
				 .eq(UserOrder::getUserId, userOrder.getUserId())
				 .eq(UserOrder::getPaid, 1)// 支付成功
				 .ne(UserOrder::getPayType, 1)// 支付方式0平台余额1平台积分2众鸟余额
				 .eq(UserOrder::getAwardIntegral,1)//积分商品
				 .last("ORDER BY id asc limit 1")
				 );
				 if (oneUserOrder!=null && oneUserOrder.size()>0) {
				 UserOrder tempOrder = oneUserOrder.get(0);
				 BigDecimal integral = tempOrder.getPvTotalPrice();
				 if (integral.compareTo(referrer.getOrdersTotal()) > -1) {
				 //积分大于等于推荐人消费总额时，奖励当前推荐人消费金额相等积分
				 integral = referrer.getOrdersTotal();
				 }
				 userService.inIntegral(integral, referrer.getId());

				 referrerIntegral = referrerIntegral.add(integral);
				 //积分奖励记录
				 userBillService.insertBill(
				 referrer.getTenantId(),
				 referrer.getId(),
				 user.getId(),
				 userOrder.getId(),
				 1,//0转出1转入
				 integral,
				 BigDecimal.ZERO,
				 "积分奖励",
				 1,//0现金1积分2贡献值
				 2,//0增加1减少2奖励3兑换4充值5提现6购物7转账8红包9收益10运费
				 referrerIntegral,
				 "第一单积分奖励,订单[" + userOrder.getId() + "],积分[" + integral + "],手续费[" + BigDecimal.ZERO + "],实际到账[" + integral + "],余额[" + referrerIntegral + "]"
				 );
				 }
				 }else {
				 System.out.println(userOrder.getId()+"：非第一单，不给上级奖励积分");
				 }
				 **/
				System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>开始赠送推荐人贡献值");
				// TODO 三.赠送推荐人贡献值
				if (userOrder.getAwardContribute() == 1) {
					JSONObject contributeValue = JSONObject.parseObject(ParamCache.getValue("contribute.value"));
					if (contributeValue instanceof JSONObject) {
						JSONArray rule = contributeValue.getJSONArray("rule");
						if (rule instanceof JSONArray) {
							//系数=贡献值现值/贡献值基质-1
							BigDecimal multiple = contributeValue.getBigDecimal("now").divide(contributeValue.getBigDecimal("basics"), 2, BigDecimal.ROUND_DOWN).subtract(new BigDecimal(1));
							AtomicReference<BigDecimal> ratio1 = new AtomicReference<>(BigDecimal.ZERO);
							AtomicReference<BigDecimal> ratio2 = new AtomicReference<>(BigDecimal.ZERO);
							for (int i = 0; i < rule.size(); i++) {
								JSONObject object = rule.getJSONObject(i);
								BigDecimal s = object.getJSONObject("multiple").getBigDecimal("s");
								BigDecimal n = object.getJSONObject("multiple").getBigDecimal("n");
								if (multiple.compareTo(s) > -1 && multiple.compareTo(n) < 1) {
									BigDecimal m = object.getJSONObject("ratio").getBigDecimal("m");
									BigDecimal c = object.getJSONObject("ratio").getBigDecimal("c");
									ratio1.set(m);
									ratio2.set(c);
									break;
								}
							}
							//在奖励区间范围 大于0才能获得积分
							if (ratio1.get().compareTo(BigDecimal.ZERO) > 0) {
								//奖励贡献值=订单价格/规则1*规则2
								BigDecimal contribute = userOrder.getPvTotalPrice().divide(ratio1.get(), 2, BigDecimal.ROUND_DOWN).multiply(ratio2.get());
								if (contribute.compareTo(new BigDecimal(0)) > -1) {
									userService.inContribute(contribute, referrer.getId());

//									referrerContribute = referrerContribute.add(contribute);
									//增加贡献值赠送记录
									userBillService.insertBill(
										referrer.getTenantId(),
										referrer.getId(),
										user.getId(),
										userOrder.getId(),
										1,//0转出1转入
										contribute,
										BigDecimal.ZERO,
										"贡献值奖励",
										2,//0现金1积分2贡献值
										2,//0增加1减少2奖励3兑换4充值5提现6购物7转账8红包9收益10运费
//										referrerContribute,
										"贡献值奖励,订单[" + userOrder.getId() + "],推荐[" + user.getId() + "],贡献值[" + contribute + "],手续费[" + BigDecimal.ZERO + "],实际到账[" + contribute + "]"//,余额[" + referrerContribute + "]
									);
								}
							}
						}
					}
				}
				System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>结束赠送推荐人贡献值");
			}
		}
		// TODO 五.普通会员升级VIP
		if (user.getUserSign() == 0 && userOrder.getPvTotalPrice().compareTo(onw.get(1)) > -1) {
			System.out.println(">>>>>>>>>>>>>>>>>普通会员升级");
			userService.upgrade(user.getId());
		}
		// TODO 六.服务收益（极差收益）
		if (userOrder.getAwardRange() == 1) {
			System.out.println(">>>>>>>>>>>>>>>>>服务收益（极差收益）");
//				updateTeamRevenue(user.getSpreadId(), user.getUserSign(), order.getPvTotalPrice(), order.getId());
			updateTeamRevenue(user.getSpreadId(), 0, userOrder.getPvTotalPrice(), userOrder.getId());
		}
	}

	/**
	 * 服务收益-极差收益（奖励现金）
	 * 从下往上单线返到顶级，同级跳过继续往上
	 *
	 * @param spreadId   上级用户ID
	 * @param downLevel  用户级别
	 * @param orderPrice 订单价格
	 * @return
	 */
	private BigDecimal updateTeamRevenue(Long spreadId, int downLevel, BigDecimal orderPrice, Long oid) {
		BigDecimal revenue = BigDecimal.ZERO;
		System.out.println("服务收益-极差收益（奖励现金）0>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>spreadId：" + spreadId + ",downLevel:" + downLevel + "orderPrice:" + orderPrice + ",oid:" + oid);
		User userTemp = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getUid, spreadId));
		if (userTemp != null) {
//			BigDecimal userBalance = userTemp.getSysBalance();
			if (downLevel < userTemp.getUserSign()) {
				if (downLevel == 0) {
					downLevel = 1;
				}
				// 当前用户服务收益（级别对应系数*订单金额）-下级服务收益（级别对应系数*订单金额）
				revenue = value.get(userTemp.getUserSign()).multiply(orderPrice).subtract(value.get(downLevel).multiply(orderPrice));
				// 去掉超限金额
				if (revenue.compareTo(limit.get(downLevel)) > 0) {
					revenue = limit.get(downLevel);
				}
				System.out.println("服务收益-极差收益（奖励现金）2>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + userTemp.getUserSign() + ":" + revenue);
				// 极差收益大于零 分配奖励
				if (revenue.compareTo(BigDecimal.ZERO) > 0) {
					//增加收益
					userService.inEarningsTotal(revenue, userTemp.getId());

//					userBalance = userBalance.add(revenue);
					//服务收益奖励记录
					userBillService.insertBill(
						userTemp.getTenantId(),
						userTemp.getId(),
						0L,
						oid,
						1,//0转出1转入
						revenue,
						BigDecimal.ZERO,
						"服务收益",
						0,//0现金1积分2贡献值
						9,//0增加1减少2奖励3兑换4充值5提现6购物7转账8红包9收益10运费
//						userBalance,
						"服务收益,订单[" + oid + "],推荐[" + userTemp.getId() + "],金额[" + revenue + "],手续费[" + BigDecimal.ZERO + "],实际到账[" + revenue + "]"//,余额[" + userBalance + "]
					);
				}
			}
			System.out.println("服务收益-极差收益（奖励现金）3>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + userTemp.getUserSign() + ":" + userTemp.getSpreadId());
			if (userTemp.getSpreadId() != null && userTemp.getSpreadId() != 0 && userTemp.getUserSign() < 5) {
				updateTeamRevenue(userTemp.getSpreadId(), (downLevel > userTemp.getUserSign() ? downLevel : userTemp.getUserSign()), orderPrice, oid);
			}
		}
		return revenue;
	}

	/**
	 * 分配分红资格
	 *
	 * @param userOrder
	 */
	@Override
	public void bonusStatus(UserOrder userOrder) {
		// 获取相应规则
		JSONArray memberSystemRule = JSONArray.parseArray(ParamCache.getValue("member.system.rule"));
		if (memberSystemRule instanceof JSONArray) {
			memberSystemRule.stream().forEach(x -> {
				JSONObject object = (JSONObject) x;
				num.put(object.getInteger("no"), object.getInteger("num"));
				repeat.put(object.getInteger("no"), object.getBigDecimal("repeat"));
				limit.put(object.getInteger("no"), object.getBigDecimal("limit"));
				onw.put(object.getInteger("no"), object.getBigDecimal("onw"));
				team.put(object.getInteger("no"), object.getBigDecimal("team"));
				value.put(object.getInteger("no"), object.getBigDecimal("value"));
			});
		}
		// 获取用户信息
		User user = userService.getById(userOrder.getUserId());
		// TODO 更新当前客户红包资格 当前订单金额与红包资格对比
		if (user.getBonusStatus() == 0 && userOrder.getAwardBonus() == 1 && userOrder.getPvTotalPrice().compareTo(repeat.get(user.getUserSign() == 0 ? 1 : user.getUserSign())) > -1) {
			System.out.println(">>>>>>>>>>>>>>>>>分配处理复消红包资格");
			userService.bonusStatus(1, user.getId());
		}
		if (userOrder.getPayType() == 2) {
			this.dispose(userOrder.getId());
		}
	}

	/**
	 * 给推荐人奖励第一单积分
	 *
	 * @param userOrder
	 */
	@Override
	public void awardIntegral(UserOrder userOrder) {
		// 获取用户信息
		User user = userService.getById(userOrder.getUserId());
		// 推荐人信息
		User referrer = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getUid, user.getSpreadId()));
		if (referrer != null) {
//			BigDecimal referrerIntegral = referrer.getSysIntegral();
			// 查询第一单 支付成功且非积分订单
			BigDecimal integral = userOrder.getPvTotalPrice();
			BigDecimal ordersTotal = this.ordersTotal(referrer.getId());
			if (integral.compareTo(ordersTotal) > -1) {
//			if (integral.compareTo(referrer.getOrdersTotal()) > -1) {
				//积分大于等于推荐人消费总额时，奖励当前推荐人消费金额相等积分
				integral = ordersTotal;//referrer.getOrdersTotal();
			}
			userService.inIntegral(integral, referrer.getId());

//			referrerIntegral = referrerIntegral.add(integral);
			//积分奖励记录
			userBillService.insertBill(
				referrer.getTenantId(),
				referrer.getId(),
				userOrder.getUserId(),
				userOrder.getId(),
				1,//0转出1转入
				integral,
				BigDecimal.ZERO,
				"积分奖励",
				1,//0现金1积分2贡献值
				2,//0增加1减少2奖励3兑换4充值5提现6购物7转账8红包9收益10运费
//				referrerIntegral,
				"第一单积分奖励,订单[" + userOrder.getId() + "],积分[" + integral + "],手续费[" + BigDecimal.ZERO + "],实际到账[" + integral + "]"//,余额[" + referrerIntegral + "]
			);
		}
	}

	/**
	 * 获取订单总额
	 * @param userId
	 */
	@Override
	public BigDecimal ordersTotal(Long userId){
		return baseMapper.ordersTotal(userId);
	}

	/**
	 * 获取公益订单总额
	 * @param userId
	 */
	@Override
	public BigDecimal bonusOrdersTotal(Long userId){
		return baseMapper.bonusOrdersTotal(userId);
	}

	/**
	 * 获取订单总额
	 */
	@Override
	public BigDecimal sumPayPrice(){
		return baseMapper.sumPayPrice();
	}
}
